<template>
  <pageHeader
    :title="route.query.saveId ? '修改产品工艺路线' : '新增产品工艺路线'"
    :breadCrumb="['工厂建模', '工艺路线管理', '工艺路线管理']"
    :show-back="true"
    ><template #footer>
      <a-space :size="20">
        <a-button @click="router.back()">取消</a-button>
        <a-button type="primary" @click="handleOk">保存</a-button>
      </a-space>
    </template>
    <a-spin :loading="loading" class="cantainer">
      <a-form :model="formData" ref="refForm" auto-label-width class="form">
        <a-row :gutter="15">
          <a-col :span="formData.id ? 12 : 8">
            <a-form-item
              label="工艺路线版本号:"
              field="routerName"
              :rules="getRules('工艺路线版本号')"
            >
              <a-input v-model="formData.routerName" />
            </a-form-item>
          </a-col>
          <a-col :span="formData.id ? 12 : 8">
            <a-form-item
              label="关联产品:"
              field="productId"
              :rules="getRules('产品')"
            >
              <ProductChoice
                @choice="choiceProductChoice"
                :disabled="!!route.query.saveId || !!route.query.historyId"
                v-model:value="formData.productId"
                ref="refProductChoice"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8" v-if="!formData.id">
            <a-form-item label="预设工艺路线">
              <ProcessRouteChoice @choice="processRouteChoice">
                <a-button type="primary">引用预设工艺路线</a-button>
              </ProcessRouteChoice>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <GroupDataConfig ref="refGroupDataConfig" />
    </a-spin>
  </pageHeader>
</template>

<script setup lang="ts">
  import { Message } from '@arco-design/web-vue';
  import { reactive, onMounted, ref, nextTick } from 'vue';
  import {
    GetProductProcessRoute,
    AddProductProcessRoute,
    EditProductProcessRoute,
    GetProductProcessRoutePage,
    GetProcessRoute,
  } from '@/api/FactoryModeling';
  import { useRoute, useRouter } from 'vue-router';
  import {
    TProductProcessRoute,
    TProcessRoute,
  } from '@/api/FactoryModeling/type';
  import ProcessRouteChoice from '@/views/client-side/FactoryModeling/components/ProcessRouteChoice.vue';
  import GroupDataConfig from './GroupDataConfig.vue';

  let route = useRoute();
  let router = useRouter();
  let refGroupDataConfig = ref();
  let loading = ref(false);
  let formData = reactive<TProductProcessRoute>({ history: 1 });
  let getRules = (name?: string) => {
    return [{ required: true, message: (name || '') + '不能为空' }];
  };

  let refForm = ref();
  let handleOk = async () => {
    try {
      let [check1, check2] = await Promise.all([
        refForm.value.validate(),
        refGroupDataConfig.value.getGroupData(),
      ]);
      if (!!check1 || !check2) return;
      let data: TProductProcessRoute = {
        ...formData,
        groupData: check2.map((item: any, index: any) => {
          return { ...item, sort: index + 1 };
        }),
      };
      let res = formData.id
        ? await EditProductProcessRoute(data)
        : await AddProductProcessRoute(data);
      router.back();
    } catch (err) {
      console.log(err);
    }
  };

  let refProductChoice = ref();
  onMounted(async () => {
    if (!route.query.saveId && !route.query.copyId && !route.query.historyId)
      return refGroupDataConfig.value.setGroupData();

    refProductChoice.value.inputValue = route.query.productName;
    loading.value = true;
    try {
      let res = await GetProductProcessRoute({
        id: route.query.saveId || route.query.copyId || route.query.historyId,
      });
      refGroupDataConfig.value.setGroupData(
        res.groupData,
        route.query.copyId || route.query.historyId
      );
      Object.assign(formData, {
        ...res,
        productId: route.query.copyId ? undefined : res.productId,
        history: route.query.historyId ? 2 : res.history || 1,
        id: route.query.copyId || route.query.historyId ? undefined : res.id,
        state: 0,
      });
    } catch (err) {
      console.error(err);
    }
    loading.value = false;
  });

  let choiceProductChoice = async ({ id }: any) => {
    let res = await GetProductProcessRoutePage({
      page: 1,
      size: -1,
      history: 1,
    });
    if (res.content?.some((item: any) => item.productId === id)) {
      Message.error('该物料已经定义');
      formData.productId = 0;
    } else {
      formData.productId = id;
    }
  };
  let processRouteChoice = async ({ id }: TProcessRoute) => {
    let res: TProcessRoute = await GetProcessRoute({ id });
    refGroupDataConfig.value.setGroupData(
      res.groupData?.map((group, index) => {
        delete group.id;
        group.groupSet = group.groupSet?.map((item) => {
          delete item.id;
          return item;
        });
        return group;
      }) || []
    );
  };
</script>

<style scoped lang="less">
  .cantainer {
    width: 100%;
    .form {
      padding: 20px 20px 10px 20px;
    }
  }
</style>
